
Skt.SelectTool = Skt.Tool.extend({

	enable: function(editor) {
		this._elements = [];
		Skt.Tool.prototype.enable.call(this, editor);
		this.name = "select";
		this.set = null;

		// Drawing state
		this._drawing = false;
		this._c = null;
		this._x = 0;
		this._y = 0;
		this._w = 0;
		this._h = 0;
	},


	onDragstartElement: function(element, event) {
		var self = this;

		if (!element.selected) {
			element.selected = true;
			this._elements.push(element);
		}

		this._drawSelection();
		event.stopPropagation();
	},

	onDragmoveElement: function(element, event){
		event.stopPropagation();
	},

	onDragendElement: function(element, event){
		event.stopPropagation();
	},


	onDragstartCanvas: function(canvas, event){

		this._drawing = true;
		this._movingAtOnce = false;
		var pos = canvas.getPos(event);

		this._c = canvas.getRaphael().rect();
		this._x = pos.x;
		this._y = pos.y;
		this._dx = 0;
		this._dy = 0;

		this._c.attr({ 
			'x':this._x,
			'y':this._y,
			'width':2,
			'height':2,
			'fill': '#B6C4F2',
			'stroke': '#8DA4F0',
			'stroke-width':2,        
			'fill-opacity': 0.1,
		});

		if (this._elements.length == 0) {
			var box = this._c.getBBox();
			var inter = this._findIntersectedElements(canvas, box, true);
			if (inter) {
				this._drawSelection();
				this._movingAtOnce = true;
				this._c.remove();  
				this._c = null;
			}
		}
	},

	onDragmoveCanvas: function(canvas, event) {   
		if (this._drawing == true) {
			var pos = canvas.getPos(event);
			var x = this._x;
			var y = this._y;
			var dx = (pos.x-x);
			var dy = (pos.y-y);
			var signx = 1;
			var signy = 1;
			if(dx<0){
				x=pos.x;
				dx=-dx;
				signx = -1;
			}
			if(dy<0){
				y=pos.y;
				dy=-dy;
				signy = -1;
			}

			this._dx = dx;
			this._dy = dy;


			if (this._movingAtOnce) {
				if ( this.getEditor().getCurrentCanvas().getRoom().getRoomModerator().canEdit(Skt.sketchpad.getUser()) ) {
					var ft = this._set.ft;
					ft.attrs.translate = { x: dx*signx, y: dy*signy };
					ft.apply();
				}
			} else {
				this._c.attr({x:x, y:y, width:dx, height:dy});
			}
		}
	},

	onDragendCanvas: function(canvas, event){
		if(this._drawing == true){
			this._drawing = false;
			if (this._movingAtOnce) {
				if ( this._dx > 10 || this._dy > 10 ) {
					this.emptySelection();
				}
				return;
			} else {
				if (this._c == null)
					return;
				var box = this._c.getBBox();
				this._c.remove();  
				this._c = null;
				var just_one = false;
				//se verifica si solo se realizo un toque o se intenta arrastrar inmediatamente
				if ( box.width < 10 && box.height < 10 ) {
					//en caso de tener mas elementos tomados el toque los deselecciona (para tomar mas de uno deben cubrirse sin toque)
					this.emptySelection();
					// un toque solo selecciona un elemento
					just_one = true;
				}
				var found = this._findIntersectedElements(canvas, box, just_one);
			}

			if(!found){
				this.emptySelection();
				return;
			}

			this._drawSelection();
		}
	},

	_findIntersectedElements: function(canvas, box, just_one){
		var self = this;
		var found = false;
		canvas.eachElement(function(el){
			var inter = el.intersectWithBox(box);
			if(inter && $.inArray(el, self._elements) == -1 && (just_one == false || found == false)){
				self._elements.push(el);
				el.selected = true;
				el.drawBorder();
			}
			if(inter){
				found = true;
			}
		});
		return found;
	},

	disable: function(sketchpad) {
		this.emptySelection();
	},

	getSelection: function() {
		var elements = this._elements;
		var selection = [];

		for (var i=0, n=elements.length; i<n; i++)
			selection[i] = elements[i];

		return selection;
	},

	setSelection: function(selection){
		this.emptySelection();

		if(selection && selection.length){
			for(var i=0, n=selection.length; i<n; i++){
				var el = selection[i];
				this._elements.push(el);
				el.selected = true;
				el.drawBorder();
			}

			this._drawSelection();  
		}
	},

	emptySelection: function() {
		var self = this;
		var elements = self._elements;
		var map = {};

		for(var i=0, n=elements.length; i<n; i++){
			var el = elements[i];
			map[el.id] = el;
			el.selected = false;
			el.removeBorder();
		}

		if (this._set) {
			this._set.forEach(function(raphaelElement){
				var attrs = raphaelElement.attr(['stroke','fill','transform']);
				attrs['id']= raphaelElement.data("elementId");
				if(attrs.id && typeof attrs.id == "string"){
					self._canvas.updateElement(attrs.id, attrs);
				}
				return true;
			});

			if (this._edit_button)
				this._edit_button.remove();
				
			this._set.ft.unplug();
			this._set.clear();
			this._set = null;
			
//			TODO: Cambiar esto por un evento y su listener
//			this.getSketchpad().updateMiniview(this._canvas);
		}

		this._elements = [];
	},

	_drawSelection: function() {

		if(this._set){
			this._set.ft.unplug();
		}

		var raphael = this._canvas.getRaphael();
		var set = raphael.set();

		var rotable = true;
		var scalable = true;
		var elements = this._elements;
		for(var i=0, n=elements.length; i<n; i++){
			var elems = elements[i].getRaphaelElement();
			set.push.apply(set, elems);
			if(rotable && !elements[i].rotable()){
				rotable = false;
			}
			if(scalable && !elements[i].scalable()){
				scalable = false;
			}
		}

		var options = { 
				attrs: { fill: '#fff', stroke: '#8DA4F0'},
				size: 10,
				draw: ['bbox'],
				distance: 30,
				drag: false,
				rotate: false,
				scale: false
		};

		if ( this.getEditor().getCurrentCanvas().getRoom().getRoomModerator().canEdit(Skt.sketchpad.getUser())  ) {
			options['drag'] = ['self'];
			if (rotable)
				options['rotate'] = ['axisY'];
			if (scalable)
				options['scale'] = ['bboxCorners', 'bboxSides'];
		}

		set.ft = raphael.freeTransform(set, options);
		this._set = set;
	},

	_checkText: function() {
		var self = this;
		if (this._elements.length == 1) {
			var elem = this._elements[0]._element;
			this._set.push.apply(this._set, [elem]);
			if(elem['type'] == 'text'){
				// mostrar boton editar
				var x = $(elem[0]).offset().left;
				var y = $(elem[0]).offset().top;

				var edit_button = $('<div id="editTextButton"><a class="btn" href="#"><i class="icon-edit"></i></a></div>');
				this._edit_button = edit_button;
				$(document.body).append(edit_button);

				edit_button.css({
					'position':"absolute",
					'width':20, 'height':20,
					'top':y-43, 'left':x,
				})

				.click( function() {
					edit_button.remove();
					// mostrar input
					var text_old = elem.attrs['text'];
					var color = elem.attrs['fill'];
					var input = $("<textarea id='inputElement'>"+text_old+"</textarea>");
					$(document.body).append(input);
					
					input.css({
						position:"absolute",
						"width":120, "height":60,
						top:y+0, left:x+0,
						'font-size': '18pt',
						'color': color
					})
					.resizable({ minHeight: 30, minWidth: 60 })
					.focus()
					.blur( function() {
						var text = $(this).val();
						if(text.length > 0 && text != text_old){
							elem.attrs['text'] = text;
							var attrs = elem.attr(['text']);
							attrs['id']= elem.id;
							if(attrs.id && typeof attrs.id == "string"){
								self._canvas.updateElement(attrs.id, attrs);
							}
						}
						$(this).remove();
					});
				});
			}

		}
	}

});
